package org.squareland;

import java.util.Vector;

import org.squareland.entities.DwarfEntity;
import org.squareland.entities.Entity;

public class GameWorld {
	public GameWorld() {
		// TODO replace with character subclass
		character = (Entity)new DwarfEntity();
		
		world = new Vector<Entity>();
		world.add(character);
		height = 1000;
		width = 1000;
	}
	
	/**
	 * Updates world. Note that all speeds are gameUnits per second.
	 * @param timeMills time to evaluate round until.
	 */
	public void updateWorld(long timeMills) {
		long currTime = System.currentTimeMillis();
		
		for (int i = 0; i < world.size(); ++i) {
			Entity entity = world.get(i);

			// Removing old objects
			if (entity.lifetime != Entity.LIFETIME_INFTY && 
					currTime - entity.beartime > entity.lifetime) {
				world.remove(i);
				// after removal all indexes are decreased by 1
				--i;
				break;
			}
			
			// Updating positions
			entity.x += entity.speedX * timeMills / 1000;
			entity.y += entity.speedY * timeMills / 1000;
			
			for (int j = i + 1; j < world.size(); ++j) {
				if (entity.intersect(world.get(j))) {
					Entity e1 = entity;
					Entity e2 = world.get(j);
					
					entity.collisionCollpack(e2, timeMills);
					world.get(j).collisionCollpack(e1, timeMills);
				}
			}

			// Checking that no object is out of bounds
			if (entity.x < 0) entity.x = 0;
			if (entity.x > width) entity.x = width;
			if (entity.y < 0) entity.y = 0;
			if (entity.y > height) entity.y = height;
		}
	}
	
	//private Timer timer;
	public Entity character;
	public Vector<Entity> world;
	private int width;
	private int height;
}
